<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix"> <span>简略概要</span> </div>
      <el-table :data="summary" style="width: 100%">
        <el-table-column prop="action" label="策略" width="100"></el-table-column>
        <el-table-column prop="protocol" label="协议" width="100"></el-table-column>
        <el-table-column prop="port" label="端口" width="100"></el-table-column>
        <el-table-column prop="source" label="对象"></el-table-column>
        <el-table-column prop="comment" label="说明"></el-table-column>
        <el-table-column label="" align="right">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="actionSummaryRuleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
export default {
    name : 'CardFilterInputSummary',
    props : ['iptables'],
    computed : {
        summary() {
            return this.getSummaryList();
        }
    },
    methods : {
        /** 获取 Summary 列表 */
        getSummaryList() {
            let summary = [];
            for ( let i=0; i<this.iptables.filter.INPUT.chain.length; i++ ) {
                let item = this.iptables.filter.INPUT.chain[i];
                if ( 'tcp' != item.protocol && 'udp' != item.protocol ) {
                    continue;
                }

                let sum = {};
                sum.protocol = item.protocol;
                sum.port = item.dport;
                sum.source = item.source;
                sum.action = item.target;
                sum.comment = item.comment;
                if ( 'ACCEPT' == sum.action ) {
                    sum.action = '允许';
                } else if ( 'DROP' == sum.action ) {
                    sum.action = '拒绝';
                }
                sum.rule = item;
                summary.push(sum);
            }
            return summary;
        },

        /** 删除概要规则 */
        async actionSummaryRuleDelete( summary ) {
            try {
                await this.$confirm('此操作将删除该规则, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                });
            } catch {
                return;
            }

            let rule = summary.rule;
            let cmd = `sudo iptables -t ${rule.table} -D ${rule.chain} ${rule.index}`;
            
            let server = this.$store.getters.serverCurrent;
            let client = await server.getSshClient();
            await client.exec(cmd);
            this.$emit('update');
            this.$message({message: '操作成功',type: 'success'});
        },
    },
}
</script>